//封装wx.request()网络模块

module.exports = (url, method, data, header) => {
    header = header ? header : {}
    let user = wx.getStorageSync('user')
    let token = user.token ? user.token : ''
    let p = new Promise((resolve, reject) => {
        wx.request({
            url: url,
            method: method,
            data: Object.assign({}, data),
            header: {
                ...header,
                token
            },
            success(res) {
                // token失效跳转到登录页重新登录
                if (res.statusCode && res.statusCode == 401) {
                    wx.showToast({
                        title: '登录已过期，请重新登录!',
                        icon: 'none'
                    })

                    setTimeout(() => {
                        wx.clearStorageSync()
                        wx.reLaunch({
                            url: '/pages/login/login',
                        })
                    }, 2000)

                    return
                }
                resolve(res)
            },
            fail(err) {
                reject(err)
            }
        })
    })
    return p;
}